﻿using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

public class LogMsg
{

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetConsoleWindow();

    [DllImport("user32.dll", EntryPoint = "SetWindowText")]
    public static extern int SetWindowText(IntPtr hwnd, string lpString);


    public static Action<string> logCB;


    public static void SetWindowInfo(string text)
    {
        SetWindowText(GetConsoleWindow(), text);
    }

    private static void Log(string msg, LogMsgType lv)
    {
        logCB?.Invoke(msg);

        //Add Time Stamp
        msg = $"{DateTime.Now.ToLongTimeString()} [TID:{Environment.CurrentManagedThreadId}] >> {msg}";

        if (lv == LogMsgType.None)
        {
            Console.WriteLine(msg);
        }
        else if (lv == LogMsgType.Warn)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("[WARNING] " + msg);
        }
        else if (lv == LogMsgType.Error)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("[ERROR] " + msg);
        }
        else if (lv == LogMsgType.Info)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[INFO] " + msg);
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("[UNKNOWN-ERROR] " + msg + " >> Unknow LogMsg Type\n");

        }
        Console.ForegroundColor = ConsoleColor.Gray;
    }
    /// <summary>
    /// 打印信息
    /// </summary>
    /// <param name="msg"></param>
    public static void Info(string msg)
    {
        logCB?.Invoke(msg);
        Log(msg, LogMsgType.Info);
    }
    /// <summary>
    /// 打印警告
    /// </summary>
    /// <param name="msg"></param>
    public static void Warn(string msg)
    {
        logCB?.Invoke(msg);
        Log(msg, LogMsgType.Warn);
    }
    /// <summary>
    /// 打印报错
    /// </summary>
    /// <param name="msg"></param>
    public static void Error(string msg)
    {
        logCB?.Invoke(msg);
        Log(msg, LogMsgType.Error);
    }

}

public enum LogMsgType
{
    None = 0,// None
    Warn = 1,//Yellow
    Error = 2,//Red
    Info = 3//Green
}